package com.umfwechat.lightprogram.controller.my;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
import com.umfwechat.common.code.RetCode;
import com.umfwechat.common.constant.CommonConsts;
import com.umfwechat.common.constant.ConfigConsts;
import com.umfwechat.common.constant.ValueConsts;
import com.umfwechat.common.prop.UmfPropModel;
import com.umfwechat.lightprogram.vo.SetAgentMerAccstatVo;
import com.umfwechat.util.DateTimesUtil;
import com.umfwechat.util.ReqMessageUtil;
import com.umfwechat.util.StringUtil;
import com.umpay.sp.model.common.ReqMessage;
import com.umpay.sp.model.common.ResMessage;
import com.umpay.sp.model.saas.AgentPerm;
import com.umpay.sp.model.saas.SetAgentAccstat;
import com.umpay.sp.model.saas.SetAgentMerAccstat;
import com.umpay.sp.model.saas.StoreInf;
import com.umpay.sp.service.saas.remote.AgentPermServiceRemote;
import com.umpay.sp.service.saas.remote.SetAgentAccstatServiceRemote;
import com.umpay.sp.service.saas.remote.SetAgentMerAccstatServiceRemote;
import com.umpay.sp.service.saas.remote.StoreInfServiceRemote;
import com.umpay.sp.xml.XmlData;

import java.util.HashSet;
import java.util.Set;

import net.sf.json.JSONArray;
import com.umfwechat.lightprogram.vo.SetProfitPosDetail;
import com.umfwechat.lightprogram.vo.SetProfitPosList;


/**
 * 通过代理商编号查询代理商分润信息Controller
 * 第一步：非pos分润列表		第二步：非pos明细		第三步：pos列表	第四步：pos明细
 * @author zhangdaolong 2017-05-23
 * @version V1.0
 */

@Controller
@RequestMapping("/profit/queryProfit")
public class ProfitController {
	
	private static Logger logger = LoggerFactory.getLogger(ProfitController.class);
	
	//查询代理商分润交易接口
	@Resource
	private SetAgentAccstatServiceRemote setAgentAccstatServiceRemote;
	//查询分润分摊统计信息
	@Resource
	private SetAgentMerAccstatServiceRemote setAgentMerAccstatServiceRemote;
	@Resource
	private AgentPermServiceRemote agentPermServiceRemote;
	@Resource
	private StoreInfServiceRemote storeInfServiceRemote;
//	@Resource
//	private MerInfoServiceRemote merInfoService;
	private String dataSourceFlag=UmfPropModel.INSTANCE.getPropValue(ConfigConsts.DATASOURCEFLAG);

	/**
	 * 非pos列表查询	第一步
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/queryProfit")
	@ResponseBody
	public JSONObject queryProfit (HttpServletRequest request, HttpServletResponse response) throws Exception{
		JSONObject resJson= new JSONObject();
		resJson.put(CommonConsts.RETCODE, RetCode.SUCCESS);
		resJson.put(CommonConsts.RETMSG, "查询代理商分润信息成功");
		//通过流的方式获取前端的参数
		String reqJSON=  (String) request.getAttribute(CommonConsts.REQUESTDATA);
		String types=UmfPropModel.INSTANCE.getPropValue(ConfigConsts.QUERYPROFITLISTTYPES);
		JSONObject json = null;
		try {
			json = JSONObject.fromObject(reqJSON);
		} catch (Exception e) {
			resJson.put(CommonConsts.RETCODE, "0001");
			resJson.put(CommonConsts.RETMSG, "请求参数不足");
			logger.info("【非pos列表查询】----#---------#--数据转换异常--#---------#--" + e);
			return resJson;
		}	
		String agentId = (String) json.get(CommonConsts.LOGINAGENTID);//代理商编号
		String date =(String) json.get(CommonConsts.DATE);//开始日期
		String assistId =(String) json.get(CommonConsts.LOGINASSISTID);//登录账号
		
//		String userId = (String) json.get(CommonConsts.LOGINUSERID);//业务员编号
//		if(!"admin".equals(userId)){
//			boolean b = getPermission(userId,agentId,assistId,1);	//1:分润查询; 2:代理商商户查询; 3:对账文件获取
//			if(!b){
//				resJson.put(CommonConsts.RETCODE, "0001");
//				resJson.put(CommonConsts.RETMSG, "您没有操作权限");
//				return resJson;
//			}
//		}
		
		
		//查询多级代理商，获取所有下级代理商编号，包含自己代理商编号
//		Map<String, Object> resQ = queryAgentRel(agentId, "0");//0或不传-查询完整级别关系,1-查询直接下级,2-查询所有下级,3-查询直接上级,4-查询所有上级
//		String retCodeQ=(String)resQ.get("retCode");
//		if(!"0000".equals(retCodeQ)){
//			json.put(CommonConsts.RETCODE, "0001");
//			json.put(CommonConsts.RETMSG, "服务器异常，请稍后再试");
//			return json;
//		}
//		Map<String, Object> agentMetaMap =  (Map<String, Object>) resQ.get("agentMetaMap");
//		Integer min = Integer.valueOf( agentMetaMap.get("minLevel").toString()) ;
//		Integer max =  Integer.valueOf( agentMetaMap.get("maxLevel").toString()) ; 
//		StringBuffer sb = new StringBuffer();//所有代理商编号
//		for(int i = max;i<=min;i++){
//			List<String> list  = (List<String>) agentMetaMap.get("agent["+i+"]List");
//			for (String s : list) {
//				sb.append("'"+s+"',");
//			}
//		}
//		String agentIds = sb.substring(0,sb.length()-1);//代理商集合
		String agentIds = "'"+agentId+"'";//代理商集合
		String startDate8=null;
		String endDate8=null;
		try {
			Map<String, String> resMap=getFirstAndLastDay(date);
			startDate8=resMap.get(CommonConsts.FIRSTDAY);
			endDate8=resMap.get(CommonConsts.LASTDAY);
		} catch (Exception e) {
			resJson.put(CommonConsts.RETCODE, "0001");
			resJson.put(CommonConsts.RETMSG, "非pos列表查询代理商分润信息日期输入格式有误");
			logger.error("非pos列表查询代理商分润信息日期输入格式有误", e);
			return resJson;
		}
		ReqMessage req = ReqMessageUtil.makeSpReq();
		//向service中输入请求参数
		req.put(XmlData.AGENTID_S, agentIds);
		req.put(CommonConsts.TYPES, types);//文档中字段key为types 文档与接口不一致 非pos对应的产品类型为10，11
		req.put(CommonConsts.START_DATE, startDate8);
		req.put(CommonConsts.END_DATE, endDate8); 
		ResMessage res = null;
		try {
			//调用非pos列表查询代理商分润信息接口
			logger.info("【非pos分润列表查询】入参："+req.toString());
			res = setAgentAccstatServiceRemote.getAccstatListByMerIdAndDate(req);
			logger.info("【非pos分润列表查询】出参："+res.toString());
		} catch (Exception e) {
			resJson.put(CommonConsts.RETCODE, "0001");
			resJson.put(CommonConsts.RETMSG, "非pos分润列表查询代理商分润信息异常，请稍后重试");
			logger.error("【非pos分润列表查询】非pos分润列表查询代理商分润信息失败", e);
			return resJson;
		}
		//判断返回码是否是0000
		String code = res.getRetCode();
		Map<String, Object> productList=new HashMap<String, Object>();
		//如果没有想要的查询数据的话，返回的list中的数据是空，并不是null；		
		List<SetAgentAccstat> accstatList = (List<SetAgentAccstat>)res.getResMap().get(CommonConsts.ACCSTATLIST);
		if(code.equals(RetCode.SUCCESS)){
			BigDecimal amount=new BigDecimal("0");
			BigDecimal fullProfitAmt=new BigDecimal("0");
			BigDecimal profitAmt=new BigDecimal("0");
			BigDecimal preProfitArray=new BigDecimal("0");
			BigDecimal sufProfitArray=new BigDecimal("0");
			BigDecimal profitRate=new BigDecimal("0");
//			BigDecimal quickPay=new BigDecimal("0");
			BigDecimal qPayAlipay=new BigDecimal("0");
			BigDecimal companyPay=new BigDecimal("0");
			BigDecimal qPayWePay=new BigDecimal("0");
			BigDecimal officialAccPay=new BigDecimal("0");
			BigDecimal debitCardQPay=new BigDecimal("0");
			
			BigDecimal creditCardQPay=new BigDecimal("0");
			BigDecimal perObankPay=new BigDecimal("0");
			BigDecimal enterOBankPay=new BigDecimal("0");
			BigDecimal weAppPay=new BigDecimal("0");
			BigDecimal weScanpay=new BigDecimal("0");
			
			BigDecimal aliScanPay=new BigDecimal("0");
			BigDecimal idAuthPay=new BigDecimal("0");
			BigDecimal bCardVerifyPay=new BigDecimal("0");
			String remark=null;
			if(code.equals(RetCode.SUCCESS)&&accstatList.size()>0){
				//通过循环求所有商户的分润信息
				for(SetAgentAccstat s:accstatList){				
					BigDecimal amount1=new BigDecimal(s.getAmount());//交易总额
					BigDecimal fullProfitAmt1=new BigDecimal(s.getFullProfitAmt());//全额分润金额
					BigDecimal profitAmt1=new BigDecimal(s.getProfitAmt());//实际分润金额
					remark=s.getRemark();//交易总额区间 "500000.0~0.0"
					if(remark != null && remark.length()>0){
						String [] profitArray=remark.split(CommonConsts.INTERVAL_CONNECTOR,2);
						BigDecimal preProfitArray1=new BigDecimal(profitArray[0].toString());//前缀500000.0
						BigDecimal sufProfitArray1=new BigDecimal(profitArray[1].toString());//后缀0.0
						preProfitArray=preProfitArray.add(preProfitArray1);
						sufProfitArray=sufProfitArray.add(sufProfitArray1);
					}
					BigDecimal profitRate1=new BigDecimal(s.getProfitRate());//交易总额分润系数
					storeProductList(productList, s,qPayAlipay,companyPay,qPayWePay,
							officialAccPay,debitCardQPay,creditCardQPay,perObankPay,enterOBankPay,
							weAppPay,weScanpay,aliScanPay,idAuthPay,bCardVerifyPay);
					amount=amount.add(amount1);
					fullProfitAmt=fullProfitAmt.add(fullProfitAmt1);
					profitAmt=profitAmt.add(profitAmt1);
					profitRate=profitRate.add(profitRate1);
				}				
			}
			resJson.put(CommonConsts.FULLPROFITAMT, fullProfitAmt.toString());
			resJson.put(CommonConsts.PROFITAMT, profitAmt.toString());
			resJson.put(CommonConsts.AMOUNT,amount.toString());
			remark= preProfitArray.toString()+CommonConsts.INTERVAL_CONNECTOR+sufProfitArray.toString();
			resJson.put(CommonConsts.REMARK, remark);
			resJson.put(CommonConsts.PROFITRATE, profitRate.toString());
//			resJson.put(CommonConsts.QUICKPAY, quickPay.toString());
			resJson.put("productList", productList);
		}else{
//			logger.info("调用查询代理商分润信息表异常失败："+s.getAmount());
			resJson.put(CommonConsts.RETCODE, "0001");
			resJson.put(CommonConsts.RETMSG, "非pos列表查询失败，服务器异常，请稍后再试");
		}
		//获取retCode和集合中长度大于0	
		return resJson;		
	}
	private void storeProductList(Map<String, Object> productList, SetAgentAccstat s, 
			BigDecimal qPayAlipay, BigDecimal companyPay, BigDecimal qPayWePay, 
			BigDecimal officialAccPay, BigDecimal debitCardQPay, BigDecimal creditCardQPay, 
			BigDecimal perObankPay, BigDecimal enterOBankPay, BigDecimal weAppPay, 
			BigDecimal weScanpay, BigDecimal aliScanPay, BigDecimal idAuthPay, BigDecimal bCardVerifyPay) {
		if("11".equals(s.getType())){
			BigDecimal qPayAlipay1=new BigDecimal(s.getProfitAmt());//每个商户定价产品实际分润总额
			qPayAlipay=qPayAlipay.add(qPayAlipay1);
			productList.put("qPayAlipay", qPayAlipay);
		}
		if("22".equals(s.getType())){
			BigDecimal companyPay1=new BigDecimal(s.getProfitAmt());//每个商户定价产品实际分润总额
			companyPay=companyPay.add(companyPay1);
			productList.put("companyPay", companyPay);
		}
		if("10".equals(s.getType())){
			BigDecimal qPayWePay1=new BigDecimal(s.getProfitAmt());//每个商户定价产品实际分润总额
			qPayWePay=qPayWePay.add(qPayWePay1);
			productList.put("qPayWePay", qPayWePay);
		}
		if("12".equals(s.getType())){
			BigDecimal officialAccPay1=new BigDecimal(s.getProfitAmt());//每个商户定价产品实际分润总额
			officialAccPay=officialAccPay.add(officialAccPay1);
			productList.put("officialAccPay", officialAccPay);
		}
		if("13".equals(s.getType())){
			BigDecimal debitCardQPay1=new BigDecimal(s.getProfitAmt());//每个商户定价产品实际分润总额
			debitCardQPay=debitCardQPay.add(debitCardQPay1);
			productList.put("debitCardQPay", debitCardQPay);
		}
		if("14".equals(s.getType())){
			BigDecimal creditCardQPay1=new BigDecimal(s.getProfitAmt());//每个商户定价产品实际分润总额
			creditCardQPay=creditCardQPay.add(creditCardQPay1);
			productList.put("creditCardQPay", creditCardQPay);
		}
		if("15".equals(s.getType())){
			BigDecimal perObankPay1=new BigDecimal(s.getProfitAmt());//每个商户定价产品实际分润总额
			perObankPay=qPayAlipay.add(perObankPay1);
			productList.put("perObankPay", perObankPay);
		}
		if("16".equals(s.getType())){
			BigDecimal enterOBankPay1=new BigDecimal(s.getProfitAmt());//每个商户定价产品实际分润总额
			enterOBankPay=enterOBankPay.add(enterOBankPay1);
			productList.put("enterOBankPay", enterOBankPay);
		}
		if("17".equals(s.getType())){
			BigDecimal weAppPay1=new BigDecimal(s.getProfitAmt());//每个商户定价产品实际分润总额
			weAppPay=weAppPay.add(weAppPay1);
			productList.put("weAppPay", weAppPay);
		}
		if("18".equals(s.getType())){
			BigDecimal weScanpay1=new BigDecimal(s.getProfitAmt());//每个商户定价产品实际分润总额
			weScanpay=weScanpay.add(weScanpay1);
			productList.put("weScanpay", weScanpay);
		}
		if("19".equals(s.getType())){
			BigDecimal aliScanPay1=new BigDecimal(s.getProfitAmt());//每个商户定价产品实际分润总额
			aliScanPay=aliScanPay.add(aliScanPay1);
			productList.put("aliScanPay", aliScanPay);
		}
		if("20".equals(s.getType())){
			BigDecimal idAuthPay1=new BigDecimal(s.getProfitAmt());//每个商户定价产品实际分润总额
			idAuthPay=idAuthPay.add(idAuthPay1);
			productList.put("idAuthPay", idAuthPay);
		}
		if("21".equals(s.getType())){
			BigDecimal bCardVerifyPay1=new BigDecimal(s.getProfitAmt());//每个商户定价产品实际分润总额
			bCardVerifyPay=qPayAlipay.add(bCardVerifyPay1);
			productList.put("bCardVerifyPay", bCardVerifyPay);
		}
		
//		return productList;
	}
	/**
	 * 分润详情查询	第二步
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/getDetailProfit")
	@ResponseBody
	public JSONObject getDetailProfit (HttpServletRequest request, HttpServletResponse response) throws Exception{
		JSONObject resJson= new JSONObject();
		resJson.put(CommonConsts.RETCODE, RetCode.SUCCESS);
		resJson.put(CommonConsts.RETMSG, "查询分润分摊统计信息成功");
		//通过流的方式获取前端的参数
		String reqJSON=  (String) request.getAttribute(CommonConsts.REQUESTDATA);
		JSONObject json = null;
		try {
			json = JSONObject.fromObject(reqJSON);
		} catch (Exception e) {
			resJson.put(CommonConsts.RETCODE, "0001");
			resJson.put(CommonConsts.RETMSG, "获取请求参数失败");
			logger.info("【非pos分润详情查询】----#---------#--获取请求参数失败异常--#---------#--" + e);
			return resJson;
		}
 		String loginAgentId=json.optString(CommonConsts.LOGINAGENTID);//代理商编号
		String date=json.optString(CommonConsts.DATE);//日期2017-07
		String types=json.optString(CommonConsts.TYPES);//代理商类型
		String agentId=json.optString(CommonConsts.AGENTID,loginAgentId);//代理商编号
		String storeId=json.optString(CommonConsts.STOREID);//店铺编号
		//查询多级代理商，获取所有下级代理商编号，包含自己代理商编号
		Map<String, Object> resQ = queryAgentRel(agentId, "0");//0或不传-查询完整级别关系,1-查询直接下级,2-查询所有下级,3-查询直接上级,4-查询所有上级
		String retCodeQ=(String)resQ.get("retCode");
		if(!"0000".equals(retCodeQ)){
			json.put(CommonConsts.RETCODE, "0001");
			json.put(CommonConsts.RETMSG, "服务器异常，请稍后再试");
			return json;
		}
		Map<String ,Map<String ,String>> mapDate = (Map<String ,Map<String ,String>>) resQ.get("agentMap");
		Map<String, String> map2 = mapDate.get(agentId);	//获取查询代理商的信息
		String agentLevel =  map2.get("agentLevel");
		Map<String, Object> agentMetaMap =  (Map<String, Object>) resQ.get("agentMetaMap");
		Map<String, List<String>> supAgentLevelRelMap=(Map<String, List<String>>) resQ.get("supAgentLevelRelMap");
//		Integer min = Integer.valueOf( agentMetaMap.get("minLevel").toString()) ;
//		Integer max =  Integer.valueOf(agentLevel) ; //agentMetaMap.get("maxLevel").toString()
//		StringBuffer sb = new StringBuffer();//所有代理商编号
//		for(int i = max;i<=min;i++){
//			List<String> list  = (List<String>) agentMetaMap.get("agent["+i+"]List");
//			for (String s : list) {
//				sb.append("'"+s+"',");
//			}
//		}
//		String agentIds = sb.substring(0,sb.length()-1);//代理商集合
		String agentIds = "'"+agentId+"'";
		Calendar calendar= Calendar.getInstance();
		calendar.set(Calendar.YEAR, Integer.parseInt(date.substring(0, 4)));
		calendar.set(Calendar.MONTH, Integer.parseInt(date.substring(5, 7))-1);
		calendar.set(Calendar.DATE, 1);
		Date time = calendar.getTime();
		SimpleDateFormat sd=new SimpleDateFormat(DateTimesUtil.formatDay8Str);
		String startDate = sd.format(time);
		int daysOfMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
		calendar.set(Calendar.DATE, daysOfMonth);
		Date time2 = calendar.getTime();
		String endDate = sd.format(time2);
		//根据代理商编号查询所有店铺编号
		String pageNo =json.optString(CommonConsts.PAGE_NO, ValueConsts.PAGE_ONE);	//当前页
		String pageSize = json.optString(CommonConsts.PAGE_SIZE, ValueConsts.PAGE_TWENTY);	//每页条数
		Integer startNo = 0;	//计算开始行数
		Integer endNo = Integer.valueOf(pageSize)*Integer.valueOf(pageNo);	//计算结束行数
		ReqMessage req2 = ReqMessageUtil.makeSpReq();
		//向service发送的请求数据
		req2.put(XmlData.AGENTID_S, agentIds);//代理商编号
		req2.put(CommonConsts.START_DATE, startDate);//开始日期
		req2.put(CommonConsts.END_DATE, endDate);//结束日期
		req2.put(CommonConsts.TYPES, types);//代理商类型
		req2.put(CommonConsts.START_NO,startNo.toString());
		req2.put(CommonConsts.END_NO,endNo.toString());
		if(StringUtil.isNotEmpty(storeId)){
			req2.put(CommonConsts.MERIDS, "'"+storeId+"'");//店铺编号
		}
		ResMessage resMessage = null;
		try {
			//调用查询分润分摊统计信息接口
			logger.info("【非pos分润详情查询接口】入参："+req2.toString());
			resMessage = setAgentMerAccstatServiceRemote.getAccstatByMerIdAndDate(req2);
			logger.info("【非pos分润详情查询接口】出参："+resMessage.toString());
		} catch (Exception e) {
			resJson.put(CommonConsts.RETCODE, "0001");
			resJson.put(CommonConsts.RETMSG, "查询分润分摊统计信息异常，请稍后重试");
			logger.info("【非pos分润详情查询】调用查询分润分摊统计信息异常失败："+e);
			return resJson;
		}
		int hasMore=0;	//是否显示下一页
		//判断返回码是否是0000
		String code = resMessage.getRetCode();
		if (code.equals(RetCode.SUCCESS)) {
			List<SetAgentMerAccstat> accstatList = (List<SetAgentMerAccstat>) resMessage.getResMap().get(CommonConsts.SETAGENTMERACCSTATLIST);
			List<SetAgentMerAccstatVo> list =null;
			if(accstatList != null){
				if(accstatList.size()==endNo){
					hasMore=1;
				}
				list = new ArrayList<SetAgentMerAccstatVo>();
				List<String> listStoreId= new ArrayList<String>();
				for (SetAgentMerAccstat setAgentMerAccstat : accstatList) {
					if(!listStoreId.contains(setAgentMerAccstat.getMerId())){	//没有包含
						listStoreId.add(setAgentMerAccstat.getMerId());
						SetAgentMerAccstatVo accstatVo= new SetAgentMerAccstatVo();
						accstatVo.setStoreId(setAgentMerAccstat.getMerId());
						//根据店铺编号查询店铺名称
//						ReqMessage reqFind = ReqMessageUtil.makeSpReq();
//						ResMessage merInfoResForSearch =null;
//						reqFind.put("merId",setAgentMerAccstat.getMerId());
//						try {
//							logger.info("【根据店铺编号查询店铺信息接口】入参："+reqFind.toString());
//							merInfoResForSearch = merInfoService.getMerInfoAndMerExInfo(reqFind);
//							logger.info("【根据店铺编号查询店铺信息接口】出参："+merInfoResForSearch);
//						} catch (Exception e) {
//							resJson.put(CommonConsts.RETCODE, "00434101");
//							resJson.put(CommonConsts.RETMSG, "服务器异常，请稍后再试");
//							logger.info("【查询店铺详情接口】异常："+e);
//							return resJson;
//						}
//						// 获取商户信息和扩展成功后
//						if (!"0000".equals(merInfoResForSearch.getRetCode())) {
//							resJson.put(CommonConsts.RETCODE, "00434101");
//							resJson.put(CommonConsts.RETMSG, "服务器异常，请稍后再试");
//							return resJson;
//						}
//						MerInfo merInfo = (MerInfo) merInfoResForSearch.getValue("merInfo");
//						accstatVo.setStoreName(merInfo==null ? "" :merInfo.getMerName());
//						String currentAgentId = setAgentMerAccstat.getAgentId();
//						accstatVo.setAgentId(currentAgentId);//代理商编号
//						List<String> currentAgentIdList =null;
						//一级代理商没有上级
//						if(!currentAgentId.startsWith("Y") && !"".equals(currentAgentId)){
//							currentAgentIdList = supAgentLevelRelMap.get(currentAgentId);
//						}
//						accstatVo.setUpAgentId(currentAgentIdList==null ? "" : currentAgentIdList.get(0)) ;//上级代理商编号
						
						ReqMessage reqStore = ReqMessageUtil.makeSpReq();
						reqStore.put(CommonConsts.STOREID, setAgentMerAccstat.getMerId());
						ResMessage resStore =null;
						try {
							logger.info("【根据店铺编号查询店铺信息接口】入参："+reqStore.toString());
							resStore = storeInfServiceRemote.getStoreInfByPri(reqStore);	//根据店铺编号查询店铺信息
							logger.info("【根据店铺编号查询店铺信息接口】出参："+resStore);
						} catch (Exception e1) {
							resJson.put(CommonConsts.RETCODE, "0001");
							resJson.put(CommonConsts.RETMSG,"查询店铺详情接口异常");
							logger.info("【查询店铺详情接口】异常："+e1);
							return resJson;
						}
						String retCodeStore = resStore.getRetCode();
						StoreInf storeInf =null;
						if(retCodeStore.equals(RetCode.SUCCESS)){
							storeInf = (StoreInf) resStore.getResMap().get(CommonConsts.STOREINF);
							if(storeInf==null){
								storeInf =new StoreInf();
								storeInf.setStoreShortName("");
								storeInf.setAgentId("");
							}
						}else{
							resJson.put(CommonConsts.RETCODE, "00434101");
							resJson.put(CommonConsts.RETMSG, "服务器异常，请稍后再试");
							return resJson;
						}
						accstatVo.setStoreName(storeInf.getStoreShortName());
						String currentAgentId = storeInf.getAgentId();
						accstatVo.setAgentId(currentAgentId);//代理商编号
						List<String> currentAgentIdList =null;
						//一级代理商没有上级
						if(!"".equals(currentAgentId) && !currentAgentId.startsWith("Y")){
							currentAgentIdList = supAgentLevelRelMap.get(currentAgentId);
						}
						accstatVo.setUpAgentId(currentAgentIdList==null ? "" : currentAgentIdList.get(0)) ;//上级代理商编号
						accstatVo.setAmount(Double.valueOf(setAgentMerAccstat.getAmount()));
						
						accstatVo.setPtAmount(Double.valueOf(setAgentMerAccstat.getPtAmount()));
						accstatVo.setProfitAmt(Double.valueOf(setAgentMerAccstat.getProfitAmt()));
						
						accstatVo.setTtamount(Double.valueOf(setAgentMerAccstat.getTtAmount())) ;
						accstatVo.setFullProfitAmt((Double.valueOf(setAgentMerAccstat.getFullProfitAmt()))) ;
						
						accstatVo.setTransnum(Integer.valueOf(setAgentMerAccstat.getTransNum())) ;
						accstatVo.setUncapsAmt(Double.valueOf(setAgentMerAccstat.getUncapsAmt())) ;
						
						accstatVo.setPtnum(Integer.valueOf(setAgentMerAccstat.getPtNum())) ;
						accstatVo.setCapSunreacAmt(Double.valueOf(setAgentMerAccstat.getCapSunreachAmt())) ;
						
						accstatVo.setTtnum(Integer.valueOf(setAgentMerAccstat.getTtNum())) ;
						accstatVo.setCapSreachedAmt(Double.valueOf(setAgentMerAccstat.getCapSreachedAmt())) ;
						
						list.add(accstatVo);
					}else{	//包含了,就叠加
						for (SetAgentMerAccstatVo accstatVo : list) {
							if(accstatVo.getStoreId().equals(setAgentMerAccstat.getMerId())){
								double amount = accstatVo.getAmount();	//总交易额（元）
								double ptAmount = accstatVo.getPtAmount();
								double profitAmt = accstatVo.getProfitAmt();
								
								double ttamount = accstatVo.getTtamount();	//退费交易额
								double fullProfitAmt = accstatVo.getFullProfitAmt();	//总分润金额
								
								Integer transnum = accstatVo.getTransnum();	//总交易笔数
								double uncapsAmt = accstatVo.getUncapsAmt();	//非封顶分润金额
								
								Integer ptnum = accstatVo.getPtnum();
								double capSunreacAmt = accstatVo.getCapSunreacAmt();	//封顶未达分润金额
								
								Integer ttnum = accstatVo.getTtnum();	//退款交易笔数
								double capSreachedAmt = accstatVo.getCapSreachedAmt();
								
								String amount2 = setAgentMerAccstat.getAmount();
								amount+=Double.valueOf(amount2);
								accstatVo.setAmount(amount);
								
								String ptAmount2 = setAgentMerAccstat.getPtAmount();
								ptAmount+=Double.valueOf(ptAmount2);
								accstatVo.setPtAmount(ptAmount);
								
								String profitAmt2 = setAgentMerAccstat.getProfitAmt();
								profitAmt+=Double.valueOf(profitAmt2);
								accstatVo.setProfitAmt(profitAmt);
								
								String fullProfitAmt2 = setAgentMerAccstat.getFullProfitAmt();
								fullProfitAmt+=Double.valueOf(fullProfitAmt2);
								accstatVo.setFullProfitAmt(fullProfitAmt);
								
								String ttAmount2 = setAgentMerAccstat.getTtAmount();
								ttamount+=Double.valueOf(ttAmount2);
								accstatVo.setTtamount(ttamount);
								
								String uncapsAmt2 = setAgentMerAccstat.getUncapsAmt();
								uncapsAmt+=Double.valueOf(uncapsAmt2);
								accstatVo.setUncapsAmt(uncapsAmt);
								
								String transNum2 = setAgentMerAccstat.getTransNum();
								transnum+=Integer.valueOf(transNum2);
								accstatVo.setTransnum(transnum);
								
								String capSunreachAmt2 = setAgentMerAccstat.getCapSunreachAmt();
								capSunreacAmt+=Double.valueOf(capSunreachAmt2);
								accstatVo.setCapSunreacAmt(capSunreacAmt);
								
								String ttNum2 = setAgentMerAccstat.getTtNum();
								ttnum+=Integer.valueOf(ttNum2);
								accstatVo.setTtnum(ttnum);
								
								String ptNum2 = setAgentMerAccstat.getPtNum();
								ptnum+=Integer.valueOf(ptNum2);
								accstatVo.setPtnum(ptnum);
								
								String capSreachedAmt2 = setAgentMerAccstat.getCapSreachedAmt();
								capSreachedAmt+=Double.valueOf(capSreachedAmt2);
								accstatVo.setCapSreachedAmt(capSreachedAmt);
								
								break;
							}
						}
					}
				}
				//对list进行排序
				Collections.sort(list, new Comparator<SetAgentMerAccstatVo>(){

					@Override
					public int compare(SetAgentMerAccstatVo o1,
							SetAgentMerAccstatVo o2) {
						if(o1.getFullProfitAmt()>o2.getFullProfitAmt()){
							return -1;
						}else{
							return 1;
						}
					}
				} );
			}//没有交易记录就不存值
			resJson.put(CommonConsts.SETAGENTMERACCSTATLIST, list);
		} else {
			resJson.put(CommonConsts.RETCODE, "0001");
			resJson.put(CommonConsts.RETMSG, resMessage.getRetMsg());
			return resJson;
		}
		resJson.put("hasMore", hasMore);	//是否显示下一页
		logger.info("【非pos分润明细】出参结果"+resJson.toString());
		return resJson;	
	}
	/**
	 * pos列表查询	第三步
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/queryProfitPosList")
	@ResponseBody
	public JSONObject queryProfitPosList (HttpServletRequest request, HttpServletResponse response) throws Exception{
		JSONObject resJson= new JSONObject();
		resJson.put(CommonConsts.RETCODE, RetCode.SUCCESS);
		resJson.put(CommonConsts.RETMSG, "成功");
//		String profitPosListUrl=PropertyUtil.getStrValue("umfWeChatPlat_appConf.properties",ConfigConsts.QUERYPROFITPOSLISTURL, "");//http://10.10.77.94:8888/offline-serv1/0172
		String profitPosListUrl=UmfPropModel.INSTANCE.getPropValue(ConfigConsts.QUERYPROFITPOSLISTURL);
//		com.umfwechat.common.ReqMessage reqMessage = ReqMessageUtil.makeReq();
//		Map<String,Object> reqMap = reqMessage.getReqMap();
//		reqMap.put("rpid", reqMessage.getRpid());
//		reqMap.put("reqDate", reqMessage.getReqDate());
//		reqMap.put("reqTime", reqMessage.getReqTime());
		Map<String, Object> reqMap = ReqMessageUtil.makeReqMap();
		String reqJSON=  (String) request.getAttribute(CommonConsts.REQUESTDATA);
//		通过流的方式获取前端的参数
		JSONObject json = null;
		json = JSONObject.fromObject(reqJSON);
		String userid = (String)json.get(CommonConsts.LOGINUSERID);//用户名
		String assistid = (String)json.get(CommonConsts.LOGINASSISTID);//代理商登录账号
		String agentId = (String)json.get(CommonConsts.LOGINAGENTID);//TODO 代理商编号 需要和前端确认
		String date = (String)json.get(CommonConsts.DATE);
		reqMap.put(CommonConsts.USER_ID, userid);
		reqMap.put(CommonConsts.ASSIST_ID, assistid);//账号
		reqMap.put(CommonConsts.AGENTID, agentId);
		reqMap.put(CommonConsts.DATASOURCE, dataSourceFlag);
		reqMap.put(CommonConsts.PAGE_NUM, ValueConsts.PAGE_ONE);
		reqMap.put(CommonConsts.PAGE_SIZE, ValueConsts.PAGE_ONE);
		reqMap.put(CommonConsts.PROFITSBEGINMONTH, date.substring(0, 4)+date.substring(5, 7));
		reqMap.put(CommonConsts.PROFITSENDMONTH, date.substring(0, 4)+date.substring(5, 7));
		
		//自测数据
//		reqMap.put("userid", CommonConsts.ADMIN);
//		reqMap.put("assistid", "DAILISHANG");//账号
//		reqMap.put(CommonConsts.AGENTID, "Y941840723");
//		reqMap.put("profitsBeginMonth", "201612");
//		reqMap.put("profitsEndMonth", "201612");
//		reqMap.put(CommonConsts.PAGE_NUM, "1");
//		reqMap.put(CommonConsts.PAGE_SIZE, "1");
//		reqMap.put(CommonConsts.DATASOURCE, "SAAS");//TODO 这个应该走配置文件
		Map<String,Object> frontResult = null;
		try {
			logger.info("【pos分润列表查询】pos列表往后台发送的profitPosListUrl为："+profitPosListUrl);
			logger.info("【pos分润列表查询】pos列表往后台发送的为reqMap数据为："+reqMap.toString());
			frontResult = com.umpay.http.platform2.HttpUtil.httpPostForm2Xml(profitPosListUrl, reqMap);//TODO 此处的url也要走配置
			logger.info("【pos分润列表查询】pos列表后台返回数据frontResult为："+frontResult);
		} catch (Exception e2) {
			resJson.put(CommonConsts.RETCODE, "0001");
			resJson.put(CommonConsts.RETMSG,"代理商pos查询列表接口异常");
			logger.info("【pos分润列表查询】代理商pos查询列表接口异常："+e2);
			return resJson;
		}
		
		List<SetProfitPosList> listStr = null;
		try {
			JSONArray jsonArray=JSONArray.fromObject(frontResult.get(CommonConsts.LISTSTR));
			listStr=JSONArray.toList(jsonArray,SetProfitPosList.class);
		} catch (Exception e) {
			logger.info("pos列表json字符串转化为对象异常");
			logger.error("pos列表json字符串转化为对象异常为"+e);
		}
		
		String retCode = (String) frontResult.get(CommonConsts.RETCODE);
		if(retCode.equals(RetCode.SUCCESS)){
			String profitsYearMonth = null;//分润月份	
			long amount = 0;   // 交易金额
			long d0FullAmt=0;   //D0全额分润
			long d0TrueAmt=0;  //D0全额实际分润
			long d1FullAmt=0 ;    //D1全额分润
			long d1TrueAmt=0; //D1全额实际分润
			long t1FullAmt=0 ;//T1全额分润
			long t1TrueAmt=0 ;   //T1全额实际分润
			long zhilianFullAmt=0 ;//直连全额分润
			long zhilianTrueAmt=0 ;   //直连全额实际分润
			long sumFullAmt=0 ;//分润总计
			long sumTrueAmt=0 ;   //实际分润金额
			if(listStr.size()>0 && listStr.get(0) != null){
				for(SetProfitPosList setProfitPosList:listStr){
					long amount1=0;
					//由于测试数据库数据不合规，加些判断
					if(setProfitPosList.getAmount()==null ||setProfitPosList.getAmount()=="" || (setProfitPosList.getAmount().contains("-"))){
						amount1=Long.valueOf("0");
					}else{
						amount1=Long.valueOf(setProfitPosList.getAmount());
					}

					long d0FullAmt1=0;
					if(setProfitPosList.getD0FullAmt()==null ||setProfitPosList.getD0FullAmt()=="" || (setProfitPosList.getD0FullAmt().contains("-")) ) {
						d0FullAmt1=Long.valueOf("0");
					}else{
						d0FullAmt1=Long.valueOf(setProfitPosList.getD0FullAmt());
					}
					
					long d0TrueAmt1=0;
					if(setProfitPosList.getD0TrueAmt()==null ||setProfitPosList.getD0TrueAmt()==""|| (setProfitPosList.getD0TrueAmt().contains("-"))){
						d0TrueAmt1=Long.valueOf("0");
					}else{
						d0TrueAmt1=Long.valueOf(setProfitPosList.getD0TrueAmt());
					}
				
					long d1FullAmt1=0;
					if(setProfitPosList.getD1FullAmt()==null || setProfitPosList.getD1FullAmt()=="" ||(setProfitPosList.getD1FullAmt().contains("-")) ) {
						d1FullAmt1=Long.valueOf("0");
					}else{
						d1FullAmt1=Long.valueOf(setProfitPosList.getD1FullAmt());
					}
				
					long d1TrueAmt1=0;
					if(setProfitPosList.getD1TrueAmt()==null ||setProfitPosList.getD1TrueAmt()==""||(setProfitPosList.getD1TrueAmt().contains("-")) ) {
						d1TrueAmt1=Long.valueOf("0");
					}else{
						d1TrueAmt1=Long.valueOf(setProfitPosList.getD1TrueAmt());
					}
					
					long t1FullAmt1=0;
					if(setProfitPosList.getT1FullAmt()==null ||setProfitPosList.getT1FullAmt()=="" ||(setProfitPosList.getT1FullAmt().contains("-")) ) {
						t1FullAmt1=Long.valueOf("0");
					}else{
						t1FullAmt1=Long.valueOf(setProfitPosList.getT1FullAmt());
					}
					
					long t1TrueAmt1=0;
					if(setProfitPosList.getT1TrueAmt()==null ||setProfitPosList.getT1TrueAmt()=="" ||(setProfitPosList.getT1TrueAmt().contains("-")) ) {
						t1TrueAmt1=Long.valueOf("0");
					}else{
						t1TrueAmt1=Long.valueOf(setProfitPosList.getT1TrueAmt());
					}
					
					long zhilianFullAmt1=0;
					if(setProfitPosList.getZhilianFullAmt()==null ||setProfitPosList.getZhilianFullAmt()==""||(setProfitPosList.getZhilianFullAmt().contains("-")) ) {
						zhilianFullAmt1=Long.valueOf("0");
					}else{
						zhilianFullAmt1=Long.valueOf(setProfitPosList.getZhilianFullAmt());
					}
					
					long zhilianTrueAmt1=0;
					if(setProfitPosList.getZhilianTrueAmt()==null ||setProfitPosList.getZhilianTrueAmt()=="" ||(setProfitPosList.getZhilianTrueAmt().contains("-"))) {
						zhilianTrueAmt1=Long.valueOf("0");
					}else{
						zhilianTrueAmt1=Long.valueOf(setProfitPosList.getZhilianTrueAmt());
					}
					
					long sumFullAmt1=0;
					if(setProfitPosList.getSumFullAmt()==null ||setProfitPosList.getSumFullAmt()==""||(setProfitPosList.getSumFullAmt().contains("-")) ) {
						sumFullAmt1=Long.valueOf("0");
					}else{
						sumFullAmt1=Long.valueOf(setProfitPosList.getSumFullAmt());
					}
					
					long sumTrueAmt1=0;
					if(setProfitPosList.getSumTrueAmt()==null ||setProfitPosList.getSumTrueAmt()=="" ||(setProfitPosList.getSumTrueAmt().contains("-"))) {
						sumTrueAmt1=Long.valueOf("0");
					}else{
						sumTrueAmt1=Long.valueOf(setProfitPosList.getSumTrueAmt());
					}
					
					amount=amount+amount1;
					d0FullAmt=d0FullAmt+d0FullAmt1;
					d0TrueAmt=d0TrueAmt+d0TrueAmt1;
					d1FullAmt=d1FullAmt+d1FullAmt1;
					d1TrueAmt=d1TrueAmt+d1TrueAmt1;
					t1FullAmt=t1FullAmt+t1FullAmt1;
					t1TrueAmt=t1TrueAmt+t1TrueAmt1;
					zhilianFullAmt=zhilianFullAmt+zhilianFullAmt1;
					zhilianTrueAmt=zhilianTrueAmt+zhilianTrueAmt1;
					sumFullAmt=sumFullAmt+sumFullAmt1;
					sumTrueAmt=sumTrueAmt+sumTrueAmt1;
					profitsYearMonth=setProfitPosList.getProfitsYearMonth();
				}			
			}
			resJson.put(CommonConsts.DATE, profitsYearMonth);
			resJson.put(CommonConsts.AMOUNT, String.valueOf(amount));
			resJson.put(CommonConsts.SUMFULLAMT, String.valueOf(sumFullAmt));
			resJson.put(CommonConsts.SUMTRUEAMT, String.valueOf(sumTrueAmt));
			resJson.put(CommonConsts.T1FULLAMT, String.valueOf(t1FullAmt));
			resJson.put(CommonConsts.T1TRUEAMT, String.valueOf(t1TrueAmt));
			resJson.put(CommonConsts.D0FULLAMT, String.valueOf(d0FullAmt));
			resJson.put(CommonConsts.D0TRUEAMT, String.valueOf(d0TrueAmt));
			resJson.put(CommonConsts.D1FULLAMT, String.valueOf(d1FullAmt));
			resJson.put(CommonConsts.D1TRUEAMT, String.valueOf(d1TrueAmt));
			resJson.put(CommonConsts.ZHILIANFULLAMT, String.valueOf(zhilianFullAmt));
			resJson.put(CommonConsts.ZHILIANTRUEAMT,String.valueOf(zhilianTrueAmt));
			
		} else{
			resJson.put(CommonConsts.RETCODE, "0001");
			resJson.put(CommonConsts.RETMSG, "pos查询列表服务器异常，请稍后再试");
		}
		logger.info("【pos分润列表查询】resJson:" +resJson);
		return resJson;
	}
	/**
	 * pos分润详情	第四步
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/queryProfitPosDetail")
	@ResponseBody
	@SuppressWarnings("unchecked")
	public  JSONObject queryProfitPosDetail (HttpServletRequest request, HttpServletResponse response) throws Exception{

		JSONObject json= new JSONObject();
		json.put(CommonConsts.RETCODE, RetCode.SUCCESS);
		json.put(CommonConsts.RETMSG, "成功");
//		String profitPosDetailUrl=PropertyUtil.getStrValue("umfWeChatPlat_appConf.properties","queryProfitPosDetailUrl", "");//http://10.10.77.94:8888/offline-serv1/11112
		String profitPosDetailUrl=UmfPropModel.INSTANCE.getPropValue(ConfigConsts.QUERYPROFITPOSDETAILURL);
//		com.umfwechat.common.ReqMessage reqMessage = ReqMessageUtil.makeReq();
//		Map<String,Object> reqMap = reqMessage.getReqMap();
//		reqMap.put("rpid", reqMessage.getRpid());
//		reqMap.put("reqDate", reqMessage.getReqDate());
//		reqMap.put("reqTime", reqMessage.getReqTime());
		Map<String, Object> reqMap = ReqMessageUtil.makeReqMap();
		String reqJSON=  (String) request.getAttribute(CommonConsts.REQUESTDATA);

		JSONObject param=JSONObject.fromObject(reqJSON);
		String userid = (String)param.get(CommonConsts.LOGINUSERID);//用户名
		String assistid = (String)param.get(CommonConsts.LOGINASSISTID);//代理商登录账号
		String agentId = (String)param.get(CommonConsts.LOGINAGENTID);//TODO 代理商编号 需要和前端确认
		String pageNum=(String)param.get(CommonConsts.PAGE_NUM);//当前页
		String pageSize=(String)param.get(CommonConsts.PAGE_SIZE);//页面显示的个数
		String profitsYearMonth=(String)param.get(CommonConsts.DATE);
		String ttype = (String)param.get(CommonConsts.TYPES);//明细类型
		
		reqMap.put(CommonConsts.USER_ID, userid);
		reqMap.put(CommonConsts.ASSIST_ID, assistid);//账号
		reqMap.put(CommonConsts.AGENTID, agentId);
		reqMap.put(CommonConsts.PAGE_NUM, pageNum);
		reqMap.put(CommonConsts.PAGE_SIZE, pageSize);
		reqMap.put(CommonConsts.PROFITSYEARMONTH, profitsYearMonth.substring(0, 4)+profitsYearMonth.substring(5, 7));
		reqMap.put(CommonConsts.TTYPE, ttype);
		reqMap.put(CommonConsts.DATASOURCE, dataSourceFlag);
		
//		reqMap.put("userid", CommonConsts.ADMIN);
//		reqMap.put("assistid", "jgj");//账号
//		reqMap.put(CommonConsts.AGENTID, "Y672450043");//Y672450043
//		reqMap.put(CommonConsts.PAGE_NUM, "1");
//		reqMap.put(CommonConsts.PAGE_SIZE, "10");
//		reqMap.put("profitsYearMonth", "201503");
//		reqMap.put("ttype", "0");
//		reqMap.put(CommonConsts.DATASOURCE, "SAAS");
		
		Map<String,Object> frontResult = null;
		try {
			logger.info("【pos分润详情】调用pos详情的后台url为："+profitPosDetailUrl);
			logger.info("【pos分润详情】调用pos详情的后发送数据reqMap为："+reqMap.toString());
			frontResult = com.umpay.http.platform2.HttpUtil.httpPostForm2Xml(profitPosDetailUrl, reqMap);
			logger.info("【pos分润详情】调用pos详情返回的数据frontResult为："+frontResult);
		} catch (Exception e2) {
			json.put(CommonConsts.RETCODE, "0001");
			json.put(CommonConsts.RETMSG,"调用pos详情接口异常");
			logger.info("【调用pos详情接口】异常："+e2);
			return json;
		}
		List<SetProfitPosDetail> listStr = null;
		try {
			JSONArray jsonArray=JSONArray.fromObject(frontResult.get(CommonConsts.LISTSTR));
			listStr=JSONArray.toList(jsonArray,SetProfitPosDetail.class);
		} catch (Exception e) {
			logger.info("【pos分润详情】解析返回的listStr的json字符串异常"+e);
			json.put(CommonConsts.RETCODE, "0001");
			json.put(CommonConsts.RETMSG,"调用pos详情接口异常");
			return json;
		}	
		//获取返回码
		String retCode = (String) frontResult.get(CommonConsts.RETCODE);
		if(retCode.equals(RetCode.SUCCESS)){
			String storeName=null;//店铺名称
			long amount=0;
			long agentFee=0;
			long transNum=0;
			long fullProfitAmt=0;
			String upAgentName=null;//上级代理商
			String upupAgentName=null;//顶级代理商
			String proviceName=null;//归属省份
			String merchantClass=null;//商户类别
			String profitsYearMonth1=null;//分润月份
			BigDecimal jFeeRate=new BigDecimal("0");
			long jFeeMax=0;	
			long profitAmt=0;
			BigDecimal dFeeRate=new BigDecimal("0");
			List<SetProfitPosDetail> list =new ArrayList<SetProfitPosDetail>();
			if(listStr.size()>0 && listStr.get(0)!= null){
				String merId=null;		
				Set<String> listMerId=new HashSet();
				for(SetProfitPosDetail setProfitPosDetail2 : listStr){
					merId = setProfitPosDetail2.getMerId();
					listMerId.add(merId);
				}
				
				for(String merId3:listMerId ){
					amount=0;
					agentFee=0;
					fullProfitAmt=0;
					transNum=0;
					profitAmt=0;
					jFeeMax=0;
					dFeeRate=new BigDecimal("0");
					jFeeRate=new BigDecimal("0");
					boolean flag=false;		
					for(SetProfitPosDetail setProfitPosDetail : listStr){
						if(!flag){
							storeName=setProfitPosDetail.getMerName();//店铺名称
							upAgentName = setProfitPosDetail.getUpAgentName();
							upupAgentName = setProfitPosDetail.getUpupAgentName();
							proviceName = setProfitPosDetail.getProviceName();
							merchantClass = setProfitPosDetail.getMerchantClass();
							profitsYearMonth1=setProfitPosDetail.getProfitsYearMonth();
						}
						String agentFee1=setProfitPosDetail.getAgentFee();//手续费
						String fullProfitAmt1 = setProfitPosDetail.getFullProfitsAmt();//全额分润金额
						String transnum1 = setProfitPosDetail.getTransNum();//交易总笔数
						String profitAmt1 = setProfitPosDetail.getTrueProfitsAmt();//实际分润金额
						String amount1=setProfitPosDetail.getAmount();
						BigDecimal dFeeRate1 =new BigDecimal(setProfitPosDetail.getdFeeRate());//贷记卡费率
						BigDecimal jFeeRate1 = new BigDecimal(setProfitPosDetail.getjFeeRate());//借记卡费率
						String jFeeMax1 = setProfitPosDetail.getjFeeMax();//借记卡封顶				
						if(merId3.equals(setProfitPosDetail.getMerId())){
							flag=true;							
							amount=amount+Long.valueOf(amount1);
							fullProfitAmt=fullProfitAmt+Long.valueOf(fullProfitAmt1);
							transNum=transNum+Long.valueOf(transnum1);
							profitAmt=profitAmt+Long.valueOf(profitAmt1);
							agentFee=agentFee+Long.valueOf(agentFee1);
							jFeeMax=jFeeMax+Long.valueOf(jFeeMax1);
							dFeeRate=dFeeRate.add(dFeeRate1);
							jFeeRate=jFeeRate.add(jFeeRate1);
							
							storeName=setProfitPosDetail.getMerName();//店铺名称
							upAgentName = setProfitPosDetail.getUpAgentName();
							upupAgentName = setProfitPosDetail.getUpupAgentName();
							proviceName = setProfitPosDetail.getProviceName();
							merchantClass = setProfitPosDetail.getMerchantClass();
							profitsYearMonth1=setProfitPosDetail.getProfitsYearMonth();
						}						
					}		
				SetProfitPosDetail setProfitPosDetail1=new SetProfitPosDetail();
				setProfitPosDetail1.setMerId(merId3.trim());
				setProfitPosDetail1.setAmount(String.valueOf(amount).trim());
				setProfitPosDetail1.setAgentFee(String.valueOf(agentFee).trim());
				setProfitPosDetail1.setFullProfitsAmt(String.valueOf(fullProfitAmt).trim());
				setProfitPosDetail1.setTransNum(String.valueOf(transNum).trim());
				setProfitPosDetail1.setTrueProfitsAmt(String.valueOf(profitAmt).trim());
				if(storeName.equals("\"null\"")){
					setProfitPosDetail1.setMerName(null);
				}else{
					setProfitPosDetail1.setMerName(storeName.trim());	
				}
				if(upAgentName.equals("\"null\"")){
					setProfitPosDetail1.setUpAgentName(null);	
				}else{		
					setProfitPosDetail1.setUpAgentName(upAgentName.trim());
				}	
				if(upupAgentName.equals("\"null\"")){
					setProfitPosDetail1.setUpupAgentName(null);				
				}else{			
					setProfitPosDetail1.setUpupAgentName(upupAgentName.trim());
				}
				if(proviceName.equals("\"null\"")){
					setProfitPosDetail1.setProviceName(null);
				}else{
					setProfitPosDetail1.setProviceName(proviceName.trim());
				}
				if(merchantClass.equals("\"null\"")){
					setProfitPosDetail1.setMerchantClass(null);
				}else{
					setProfitPosDetail1.setMerchantClass(merchantClass.trim());
				}
				if(profitsYearMonth1.equals("\"null\"")){
					setProfitPosDetail1.setProfitsYearMonth(null);
				}else{
					setProfitPosDetail1.setProfitsYearMonth(profitsYearMonth1.trim());
				}
				
				setProfitPosDetail1.setjFeeMax(String.valueOf(jFeeMax).trim());
				setProfitPosDetail1.setjFeeRate(String.valueOf(jFeeRate).trim());
				setProfitPosDetail1.setdFeeRate(String.valueOf(dFeeRate).trim());
				list.add(setProfitPosDetail1);
				json.put(CommonConsts.LIST_STR, list);
				}
			}else{
				SetProfitPosDetail setProfitPosDetail1=new SetProfitPosDetail();
				setProfitPosDetail1.setMerId(null);
				setProfitPosDetail1.setAmount(String.valueOf(0));
				setProfitPosDetail1.setMerName(null);
				setProfitPosDetail1.setAgentFee(String.valueOf(agentFee).trim());
				setProfitPosDetail1.setFullProfitsAmt(String.valueOf(fullProfitAmt).trim());
				setProfitPosDetail1.setTransNum(String.valueOf(transNum).trim());
				setProfitPosDetail1.setTrueProfitsAmt(String.valueOf(profitAmt).trim());
				setProfitPosDetail1.setUpAgentName(null);
				setProfitPosDetail1.setUpupAgentName(null);
				setProfitPosDetail1.setProviceName(null);
				setProfitPosDetail1.setMerchantClass(null);
				setProfitPosDetail1.setProfitsYearMonth(null);
				setProfitPosDetail1.setjFeeMax(String.valueOf(jFeeMax).trim());
				setProfitPosDetail1.setjFeeRate(String.valueOf(jFeeRate).trim());
				setProfitPosDetail1.setdFeeRate(String.valueOf(dFeeRate).trim());
				list.add(setProfitPosDetail1);
				json.put(CommonConsts.LIST_STR, list);			
			}			
		}else{
			json.put(CommonConsts.RETCODE, "0001");
			json.put(CommonConsts.RETMSG, "服务器异常，请稍后再试");
		}
		return json;			
		}
	/**
	 * 根据开始日期年份和月份，求取当月的第一天和当月的最后一天 
	 * 先求当月的第一天，让后把月份加1，天数减1，求得就是当月的最后一天
	 */
	private Map<String, String> getFirstAndLastDay (String inputDate) throws Exception {
		Map<String, String> resMap=new HashMap();
		Calendar cl = new GregorianCalendar();
		//求出输入日期的time 根据输入时期（2015-03）求出time
		DateFormat inputFormat = new SimpleDateFormat(DateTimesUtil.formatDay6Str);
		String convertDate=inputDate.substring(0, 4)+inputDate.substring(5, 7);
		Date startDate=inputFormat.parse(convertDate);
		cl.setTime(startDate);
		//输出的格式
		SimpleDateFormat outPutFormat1 = new SimpleDateFormat(DateTimesUtil.formatDay8Str);
        String fDay = outPutFormat1.format(cl.getTime());
        resMap.put(CommonConsts.FIRSTDAY, fDay);
        //当月的最后一天
        cl.add(Calendar.MONTH, 1);
        cl.add(Calendar.DAY_OF_MONTH,-1);
		SimpleDateFormat outPutFormat2 = new SimpleDateFormat(DateTimesUtil.formatDay8Str);
		String lDay=outPutFormat2.format(cl.getTime());
		resMap.put(CommonConsts.LASTDAY, lDay);
		return resMap;
	}	
	public static void main(String[] args) {
		SetAgentMerAccstatVo accstatVo=new SetAgentMerAccstatVo();
		accstatVo.setAmount(100);
		double ss = accstatVo.getAmount();
		System.out.println(ss);
		ss = ss+100;
		System.out.println(ss);
		
		System.out.println(accstatVo.getAmount());
		
	}
	private Map<String, Object> queryAgentRel(String agentId,String type) {
	    Map<String, Object> req = ReqMessageUtil.makeReqCrmMap();
	    req.put("agentId", agentId);
	    req.put("relType", type);
		Map<String, Object> res = null;
		try {
			XStream xstream = new XStream(new DomDriver());
			// URL配置文件取
			String url=UmfPropModel.INSTANCE.getPropValue("agent.crm.queryAgentRel");
			//调用受理注销用户标识接口
			logger.info("【查询代理商多级关系接口】入参：" + req.toString()+"请求路径url="+url);
			res =  (Map<String, Object>) com.umfwechat.util.HttpUtil.getResObjPost(url, xstream, req);	
		} catch (Exception e) {
			logger.info("【调用查询代理商多级关系接口失败!】",e);
			res.put(CommonConsts.RETCODE, "0001");
			res.put(CommonConsts.RETMSG,"服务器异常，请稍后再试");	
			return res;
		}
		if(res==null){
			res.put(CommonConsts.RETCODE, "0001");
			res.put(CommonConsts.RETMSG, "服务器异常，请稍后再试");
			return res;
		}
		logger.info("【查询代理商多级关系接口】出参：" + res.toString());				
		return res;
	}
	/**
	 * @param salesmanId业务员名称
	 * @param agentId代理商编号
	 * @param assistId登录账号
	 * @param type菜单类型(1:分润查询; 2:代理商商户查询; 3:对账文件获取)
	 * @return
	 */
	public boolean getPermission(String salesmanId, String agentId, String assistId, Integer type){
		com.umpay.sp.model.common.ReqMessage reqMess = ReqMessageUtil.makeSpReq();
		reqMess.put(CommonConsts.SALESMANID, salesmanId);
		reqMess.put(CommonConsts.AGENTID,agentId);
		reqMess.put(CommonConsts.ASSISTID,assistId);
		ResMessage res = null;
		try {
			logger.info("【获取代理商权限控制接口】输入参数：" + reqMess);
			res = agentPermServiceRemote.getAgentPermByPri(reqMess);
			logger.info("【获取代理商权限控制接口】输出参数：" + res);
		} catch (Exception e) {
			return false;
		}
		String retCode = res.getRetCode();
		if (!RetCode.SUCCESS.equals(retCode)) {
			return false;
		}
		AgentPerm agentPerm = (AgentPerm) res.getResMap().get("agentPerm");
		if (agentPerm == null) {
			return false;
		}
		if(type == 1){	//分润查询权限
			if("1".equals(agentPerm.getSearchProfitPerm())){
				return true;
			}
		}
		if(type == 2){	//代理商商户查询权限
			if("1".equals(agentPerm.getSearchStorePerm())){
				return true;
			}
		}
		if(type == 3){	//对账文件获取权限
			if("1".equals(agentPerm.getFetchBillDocPerm())){
				return true;
			}
		}
		return false;
	}
}
